import type { App, Directive, DirectiveBinding } from 'vue'
import { createLoading } from './createLoading'

// loading 指令定义
export const loadingDirective: Directive = {
  // 当绑定元素挂载到 DOM 中
  mounted(el, binding: DirectiveBinding<boolean>) {
    const text = el.getAttribute('loading-text') || ''
    const fullscreen = !!binding.modifiers.fullscreen

    // 创建 loading 实例（根据是否 fullscreen 选择挂载目标）
    const instance = createLoading(
      {
        text,
        loading: !!binding.value,
        fullscreen
      },
      fullscreen ? document.body : el
    )

    // 将实例绑定到元素上，便于更新/销毁使用
    el.instance = instance
  },

  // 当绑定的值变化时
  updated(el, binding: DirectiveBinding<boolean>) {
    const instance = el.instance
    if (!instance) return

    // 更新 loading 文本
    const newText = el.getAttribute('loading-text')
    if (newText !== undefined) {
      instance.setText(newText)
    }

    // 根据值变化控制 loading 状态（值为 true 表示显示）
    if (binding.oldValue !== binding.value) {
      instance.setLoading?.(!!binding.value)
    }
  },

  // 当元素卸载时，销毁 loading 实例
  unmounted(el) {
    el.instance?.close()
    delete el.instance
  }
}

// 注册 v-loading 指令的安装函数
export const setupLoadingDirective = (app: App) => {
  app.directive('loading', loadingDirective)
}
